<script setup>
import { getDefectiveCurveChart } from "@/api/visual/productionBoard";
import { fontSize } from "@/utils/globalMethod.js";

const key = ref(1);
const optionData = ref([]);
const xAxisData = ref([]);
const props = defineProps({
  // 将变量名改为props（复数形式）
  activeLineID: {
    type: String,
    default: "",
  },
  active: {
    type: String,
    default: "",
  },
});

const option = computed(() => ({
  title: {
    text: "不良曲线图",
    textStyle: {
      color: "#fff",
      fontSize: fontSize(0.16),
    },
  },
  xAxis: {
    type: "category",
    data: xAxisData.value,
    axisLabel: {
      color: "#ccc1c1",
    },
  },
  yAxis: {
    type: "value",
    splitLine: {
      lineStyle: {
        color: "#2b2c33",
      },
    },
    axisLabel: {
      color: "#ccc1c1",
    },
  },
  legend: {
    right: "0",
    textStyle: {
      color: "#ccc1c1",
    },
  },
  grid: {
    bottom: "15%",
    top: "20%",
    left: "15%",
  },
  series: optionData.value,
}));

const getLast7Days = () => {
  const days = [];
  const today = new Date();

  for (let i = 6; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(today.getDate() - i);

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");

    days.push(`${year}${month}${day}`);
  }
  return days;
};
const aggregateData = (data) => {
  const aggregated = {};
  data.forEach((item) => {
    const { BillDate, GoodQty, BadQty } = item;
    const dateKey = BillDate;

    if (!aggregated[dateKey]) {
      aggregated[dateKey] = {
        BillDate,
        BadQty: 0,
        GoodQty: 0,
      };
    }

    aggregated[dateKey].GoodQty += GoodQty;
    aggregated[dateKey].BadQty += BadQty;
  });

  // 将对象转换为数组
  return Object.values(aggregated);
};
const loadData = async () => {
  let { data } = await getDefectiveCurveChart({
    LineName: props.activeLineID,
    OrderID: props.active,
  });
  data = aggregateData(data);
  xAxisData.value = getLast7Days();
  const matchedData = xAxisData.value.map((date) => {
    // 将横坐标轴的日期转换为数字类型，以便与后端数据匹配
    const dateNum = parseInt(date);
    // 查找匹配的后端数据
    const matchedItem = data.find((item) => item.BillDate === dateNum);
    if (matchedItem) {
      return {
        date,
        GoodQty: matchedItem.GoodQty,
        BadQty: matchedItem.BadQty,
      };
    } else {
      return {
        date,
        BadQty: 0,
        GoodQty: 0,
      };
    }
  });
  const goodData = matchedData.map((item) => Number(item.GoodQty.toFixed(0)));
  const badData = matchedData.map((item) => Number(item.BadQty.toFixed(0)));
  optionData.value = [
    {
      name: "良品",
      type: "bar",
      data: goodData,
      label: {
        show: true,
        position: "top",
        color: "#fff",
        textStyle: {
          fontSize: 12,
        },
      },
      itemStyle: {
        color: "#4CAF50",
      },
    },
    {
      name: "不良品",
      type: "bar",
      data: badData,
      label: {
        show: true,
        position: "top",
        color: "#fff",
        textStyle: {
          fontSize: 12,
        },
      },
      itemStyle: {
        color: "#FF5252",
      },
    },
  ];
};
const keyResize = () => {
  nextTick(() => {
    setTimeout(() => {
      key.value++;
    }, 100);
  });
};
watch(
  () => [props.activeLineID, props.active], // 使用正确的变量名props
  async (newValues, oldValues) => {
    if (newValues !== oldValues || newValues !== oldValues) {
      await loadData();
    }
  },
  { immediate: true }
);
onMounted(loadData);

onMounted(() => {
  window.addEventListener("resize", keyResize);
});

onUnmounted(() => {
  window.removeEventListener("resize", keyResize);
});
</script>

<template>
  <div class="ps_w_h_100">
    <dv-border-box13 class="ps_pd10" :key="key">
      <ps-chart2 :option="option"></ps-chart2>
    </dv-border-box13>
  </div>
</template>

<style scoped lang="scss"></style>
